package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.util.JwtUtils;
import com.ihrm.common.util.PermissionConstants;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.ProfileResult;
import com.ihrm.domain.system.response.UserResult;
import com.ihrm.system.service.PermissionService;
import com.ihrm.system.service.RoleService;
import com.ihrm.system.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/sys")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 分配角色
     */
    @RequestMapping(value="/user/assignRole",method = RequestMethod.PUT)
    public Result assignRole(@RequestBody Map<String,Object> map){
        String userId = (String) map.get("id");
        List<String> roleIds = (List<String>) map.get("roleIds");
        userService.assignRoles(userId,roleIds);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 保存
     */
    @RequestMapping(value="/user",method = RequestMethod.POST)
    public Result save(@RequestBody User user){
        //设置企业id
        user.setCompanyId(companyId);
        user.setCompanyName(companyName);
        userService.add(user);
        return new Result(ResultCode.SUCCESS,user);
    }

    /**u
     * 查询所有
     */
    @RequestMapping(value="/user",method = RequestMethod.GET)
    public Result findAll(int page,int size,@RequestParam Map map){
        //获取当前企业id
        map.put("companyId",companyId);
        //完成查询
        Page<User> pageUser = userService.findAll(map, page, size);
        //构造返回结果
        PageResult<User> pageResult = new PageResult<>(pageUser.getTotalElements(), pageUser.getContent());

        return new Result(ResultCode.SUCCESS,pageResult);
    }

    /**
     * 根据id查询
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id){
        User user = userService.findById(id);
        //添加已具有的roleids信息
        UserResult userResult = new UserResult(user);
        return new Result(ResultCode.SUCCESS,userResult);
    }

    /**
     * 修改user
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id") String id,@RequestBody User User){
        User.setId(id);
        userService.update(User);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 删除user
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id){
        userService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 用户登陆
     *  通过service根据mobile查询用户
     *  比较password
     *  生成jwt
     */
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public Result login(@RequestBody Map<String,String> loginMap){
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");
        User u = userService.findByMobile(mobile);
        if(u == null || !u.getPassword().equals(password)){
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }else{
            //登陆成功
            //api权限字符串
            StringBuilder sb = new StringBuilder();
            //获取所有可访问api权限
            for (Role role : u.getRoles()) {
                for (Permission perm : role.getPermissions()) {
                    if(perm.getType() == PermissionConstants.PY_API){
                        sb.append(perm.getCode()).append(",");
                    }
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("apis",sb.toString());//可访问的api权限字符串
            map.put("companyId",u.getCompanyId());
            map.put("companyName",u.getCompanyName());
            String token = jwtUtils.createJwt(u.getId(), u.getMobile(), map);
            return new Result(ResultCode.SUCCESS,token);
        }

    }

    /**
     * 用户登陆成功 获取用户信息
     *  1,获取用户id
     *  2，根据用户id查询数据
     *  3，构建返回对象
     */
    @RequestMapping(value = "/profile",method = RequestMethod.POST)
    public Result profile(HttpServletRequest request) throws CommonException {

        String userId = claims.getId();
        //获取用户信息
        User user = userService.findById(userId);
        //根据不同的用户级别获取用户权限
        ProfileResult result = null;

        if("user".equals(user.getLevel())){
            result = new ProfileResult(user);
        }else{
            Map map = new HashMap();
            if("coAdmin".equals(user.getLevel())){
                map.put("enVisible","1");
            }
            List<Permission> list = permissionService.findAll(map);
            result = new ProfileResult(user,list);

        }
        return new Result(ResultCode.SUCCESS,result);
    }
}
